package com.han.fu.api.common.filter;

import com.han.fu.common.constants.RedisKeyConstants;
import com.han.fu.common.constants.StringConstants;
import com.han.fu.api.common.model.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 认证拦截
 *
 * @author star
 * @date: 2021-07-31
 */
@Component
@Slf4j
public class AuthTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisTemplate redisTemplate;

    private static final String EXPORT = "/export";

    private static final Long THIRTY = 30L;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader(StringConstants.TOKEN_HEADER);
        if (ObjectUtils.isEmpty(token)) {
            String uri = request.getRequestURI();
            if (StringUtils.hasText(uri) && uri.startsWith(EXPORT)) {
                token = request.getParameter(StringConstants.TOKEN_HEADER);
            }
        }

        // 验证token
        if (StringUtils.hasText(token)) {
            ValueOperations<String, UserDetail> valueOperations = redisTemplate.opsForValue();
            UserDetail userDetail = valueOperations.get(RedisKeyConstants.AUTH_TOKEN.concat(token));
            if (null != userDetail && null != userDetail.getId()) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                logger.info(String.format("Authenticated userDetail %s, setting security context", userDetail.getAccount()));
                SecurityContextHolder.getContext().setAuthentication(authentication);
                // token延长时间
                valueOperations.set(token, userDetail, THIRTY, TimeUnit.MINUTES);
            }
        }

        filterChain.doFilter(request, response);
    }
}
